package com.libaoxuan.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.libaoxuan.blog.dao.pojo.SysUser;
import com.libaoxuan.blog.service.RegisterService;
import com.libaoxuan.blog.utils.JWTUtil;
import com.libaoxuan.blog.vo.ErrorCode;
import com.libaoxuan.blog.vo.Result;
import com.libaoxuan.blog.vo.params.RegisterParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    SysUserServiceImpl sysUserService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public Result register(RegisterParams registerParams) {
        /**
         * 1.判断参数是否合法
         * 2.判断用户是否存在，若存在 返回账户已经被注册
         * 3.不存在，注册用户
         * 4.生成token
         * 5.存入redis 并返回
         * 6.注意 加上事务，一旦中间的任何过程出现问题，需要回滚
         */
        String account = registerParams.getAccount();
        String password = registerParams.getPassword();
        String nickname = registerParams.getNickname();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password) || StringUtils.isBlank(nickname)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        SysUser sysUser = sysUserService.findUserByAccount(account);
        if (sysUser != null) {
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        sysUser.setPassword(password);
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserService.save(sysUser);

        HashMap<String, String> payload = new HashMap<>();
        payload.put("account", sysUser.getAccount());
        String token = JWTUtil.getToken(payload);

        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        return Result.success(token);
    }
}
